package com.liyou.print;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.argox.sdk.barcodeprinter.BarcodePrinter;
import com.argox.sdk.barcodeprinter.connection.ConnectionState;
import com.argox.sdk.barcodeprinter.connection.IConnectionStateListener;
import com.argox.sdk.barcodeprinter.connection.usb.USBConnection;
import com.argox.sdk.barcodeprinter.emulation.pplb.PPLB;
import com.argox.sdk.barcodeprinter.emulation.pplb.PPLBDraw;
import com.argox.sdk.barcodeprinter.emulation.pplb.PPLBMediaType;
import com.argox.sdk.barcodeprinter.emulation.pplb.PPLBOrient;
import com.argox.sdk.barcodeprinter.emulation.pplb.PPLBPrintMode;
import com.argox.sdk.barcodeprinter.emulation.pplb.PPLBQRCodeErrCorrect;
import com.argox.sdk.barcodeprinter.emulation.pplb.PPLBQRCodeModel;
import com.argox.sdk.barcodeprinter.emulation.pplb.PPLBStorage;
import com.argox.sdk.barcodeprinter.emulation.pplz.PPLZ;
import com.argox.sdk.barcodeprinter.emulation.pplz.PPLZFont;
import com.argox.sdk.barcodeprinter.emulation.pplz.PPLZMediaTrack;
import com.argox.sdk.barcodeprinter.emulation.pplz.PPLZMediaType;
import com.argox.sdk.barcodeprinter.emulation.pplz.PPLZOrient;
import com.argox.sdk.barcodeprinter.emulation.pplz.PPLZPrintMode;
import com.argox.sdk.barcodeprinter.emulation.pplz.PPLZUnitType;
import com.argox.sdk.barcodeprinter.util.Encoding;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;


/**
 * USB打印
 *
 * @author qyf
 */
public class USBPrintModule extends UniModule {

    private static final String TAG = USBPrintModule.class.getName();
    public String CONTENT = "content";
    protected UsbDevice device = null;
    private final String ACTION_USB_PERMISSION = TAG;
    private static final Encoding encode = Encoding.UTF_8;


    /**
     * 连接打印机
     */
    @UniJSMethod(uiThread = false)
    public boolean connect() {
        if (mUniSDKInstance.getContext() instanceof Activity) {
            Activity context = (Activity) mUniSDKInstance.getContext();
            boolean flag = getUSBDevice(context);
//            final Map<String, Object> params = new HashMap<>();
//            IConnectionStateListener stateListener = state -> {
//                context.runOnUiThread(new Runnable() {
//
//                    public void run() {
//                        if (state != ConnectionState.Connected) {
//                            device = null;
//                        }
//                        params.put("state", state);
//                    }
//                });
//                Log.e(TAG, "Printer connection is " + state.name());
//            };
//            mUniSDKInstance.fireGlobalEventCallback("printDeviceChanged", params);
            return flag;


        }
        return false;
    }


    /**
     * 是否连接
     *
     * @return
     */
    @UniJSMethod(uiThread = false)
    public boolean isConnect() {
        return device != null;
    }


    /**
     * 断开连接
     *
     * @return
     */
    @UniJSMethod(uiThread = false)
    public boolean disConnect() {
        if (device != null) {
            device = null;
        }
        return true;
    }


    /**
     * 打印
     *
     * @param options
     */
    @UniJSMethod(uiThread = true)
    public void print(JSONObject options, UniJSCallback callback) {
        if (mUniSDKInstance.getContext() instanceof Activity) {
            if (device == null) {
                Log.d(TAG, device.getDeviceName() + "==============, vendorID=" + device.getVendorId());
            }
            String type = options.getString("type");
            if (type == null || type.length() == 0) {
                type = "pplb";
            }
            Activity context = (Activity) mUniSDKInstance.getContext();

            if (type.equalsIgnoreCase("pplb")) {
                PPLBFunction(options, context);
            } else {
                PPLZFunction(context);
            }

            callback.invoke(new JSONObject() {{
                put("code", 0);
                put("result", "success");
            }});
        }
    }

    @UniJSMethod(uiThread = true)
    public void printText(JSONObject options, UniJSCallback callback) {
        if (mUniSDKInstance.getContext() instanceof Activity) {
            if (device == null) {
                Log.d(TAG, device.getDeviceName() + "==============, vendorID=" + device.getVendorId());
            }
            String type = options.getString("type");
            if (type == null || type.length() == 0) {
                type = "pplb";
            }
            Activity context = (Activity) mUniSDKInstance.getContext();

            if (type.equalsIgnoreCase("pplb")) {
                PPLBFunctionText(options, context);
            } else {
                PPLZFunction(context);
            }

            callback.invoke(new JSONObject() {{
                put("code", 0);
                put("result", "success");
            }});
        }
    }

    private boolean getUSBDevice(Activity activity) {
        device = (UsbDevice) activity.getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);
        if (null == device) {
            UsbManager manager = (UsbManager) activity.getSystemService(Context.USB_SERVICE);
            HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
            for (String key : deviceList.keySet()) {
                device = deviceList.get(key);
                if (device.getVendorId() == 5732) {
                    break;
                }
            }
        }
        if (null != device) {
            UsbManager manager = (UsbManager) activity.getSystemService(Context.USB_SERVICE);
            if (!manager.hasPermission(device)) {//check permissions.
                //Notice:
                //If it is executed here, then the interface will open fail, because the device is no permission.
                //When you append the "android.hardware.usb.action.USB_DEVICE_ATTACHED" request in the XXXManifest.xml file,
                //then the system will ask for permission each time you plug in the USB.
                final PendingIntent mPermissionIntent = PendingIntent.getBroadcast(activity, 0, new Intent(ACTION_USB_PERMISSION), 0);
                manager.requestPermission(device, mPermissionIntent);
                return true;

            }
        }
        return false;

    }

    private void PPLZFunction(Activity context) {

        BarcodePrinter<USBConnection, PPLZ> printer = new BarcodePrinter<USBConnection, PPLZ>();
        try {
            //if you use BluetoothConnection instead of TCPConnection , you must implements onActivityResult(...) callback function
            //with calling printer.getConnection().onActivityResult(...)
            Log.i(TAG, "=====++++====" + device);
            printer.setConnection(new USBConnection(context, device));
            printer.setEmulation(new PPLZ());
            //printer.setEnabledLogger(true);//If you need logger file. Please enable this line code.

            printer.getConnection().open();

//            LayoutMaker maker = new LayoutMaker(this);
            String text = "Hello World!";
            //call methods that you want.
            //setting.
            printer.getEmulation().getSetUtil().setUnit(PPLZUnitType.Dot);
            printer.getEmulation().getSetUtil().setMediaTrack(PPLZMediaTrack.Non_Continuous_Mdeia_Web_Sensing);
            printer.getEmulation().getSetUtil().setOrientation(false);
            printer.getEmulation().getSetUtil().setMirror(false);
            printer.getEmulation().getSetUtil().setPrintMode(PPLZPrintMode.Tear_Off);
            printer.getEmulation().getSetUtil().setMediaType(PPLZMediaType.Direct_Thermal_Media);
            //data.
            printer.getEmulation().getTextUtil().printText(0, 0, PPLZOrient.Clockwise_0_Degrees,
                    PPLZFont.Font_Zero, 20, 20, text.getBytes(), 0);
            //set print conditions.
            printer.getEmulation().getSetUtil().setPrintOut(1, 0, 1, false);
            printer.getEmulation().printOut();
            printer.getConnection().close();
        } catch (Exception ex) {
            try {
                printer.getConnection().close();
            } catch (Exception e) {
            } finally {
                Log.e(TAG, null, ex);
            }
        }
    }


    /*
     *
     * @param printer
     * @param jsonObject
     */
    private void template(BarcodePrinter<USBConnection, PPLB> printer, JSONObject jsonObject) {
        byte[] buf;
        try {

            JSONObject content = jsonObject.getJSONObject(CONTENT);

            buf = encode.getBytes(content.getString("qrcode"));
            String headTitle = content.getString("headTitle") == null ? "" : content.getString("headTitle");
            String cusName = content.getString("cusName") == null ? "" : content.getString("cusName");
            String receiveName = content.getString("receiveName") == null ? "" : content.getString("receiveName");
            String memo = content.getString("memo") == null ? "" : content.getString("memo");
            String flagCode = content.getString("flagCode") == null ? "" : content.getString("flagCode");
            String footer = content.getString("footer") == null ? "" : content.getString("footer");
            String group = content.getString("group") == null ? "" : content.getString("group");
//            String printDate = "打印日期：2023-08-09";
            String printDate = content.getString("printDate") == null ? "" : content.getString("printDate");

            //setting.
            printer.getEmulation().getSetUtil().setHardwareOption(PPLBMediaType.Thermal_Transfer_Media, PPLBPrintMode.Peel_Off, 0);
            printer.getEmulation().getSetUtil().setOrientation(false);
            printer.getEmulation().getSetUtil().setStorage(PPLBStorage.Dram);//storage.
            printer.getEmulation().getSetUtil().setClearImageBuffer();
            printer.getEmulation().getSetUtil().setPrintWidth(850);
            printer.getEmulation().getSetUtil().setDarkness(15);

//            printer.getEmulation().getSetUtil().;
            //data.

            String imageName = "txt" + String.format("%05d", new Random().nextInt(100000));

            //表头
            if (headTitle.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                        imageName, headTitle, PPLBOrient.Clockwise_0_Degrees, 350);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 20, imageName);
            }


            //旗号
            if (flagCode.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                        imageName, flagCode, PPLBOrient.Clockwise_0_Degrees, 500);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(310, 20, imageName);
            }


            //二维码
            printer.getEmulation().getBarcodeUtil().printQRCode(600, 50, PPLBQRCodeModel.Model_2, 7, PPLBQRCodeErrCorrect.Standard, buf);// QR Code
//
//            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
//                    imageName, "---------------------------------------------------------------------------------------------------------------------------",
//                    PPLBOrient.Clockwise_0_Degrees, 500);
//            printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 40, imageName);


            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 22, false, false, false, false,
                    imageName, content.getString("qrcode"), PPLBOrient.Clockwise_0_Degrees, 200);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(580, 210, imageName);


            //绘制横线
            printer.getEmulation().getGraphicsUtil().printLine(0, 60, 500, 5, PPLBDraw.Draw_Black);
//
            //客户
            if (cusName.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 28, false, false, false, false,
                        imageName, cusName, PPLBOrient.Clockwise_0_Degrees, 600);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 80, imageName);
            }

            //收货人
            if (receiveName.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 28, false, false, false, false,
                        imageName, receiveName, PPLBOrient.Clockwise_0_Degrees, 600);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 120, imageName);
            }
            //备注
            if (memo.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 28, false, false, false, false,
                        imageName, memo, PPLBOrient.Clockwise_0_Degrees, 600);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 160, imageName);
            }

//
//            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 28, false, false, false, false,
//                    imageName, receiveAddress, PPLBOrient.Clockwise_0_Degrees, 800);
//            printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 170, imageName);
//
//            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, false, false, false, false,
//                    imageName, logo, PPLBOrient.Clockwise_0_Degrees, 200);
//            printer.getEmulation().getGraphicsUtil().printStoreGraphic(210, 550, imageName);
//
//            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, false, false, false, false,
//                    imageName, printDate, PPLBOrient.Clockwise_0_Degrees, 300);
//            printer.getEmulation().getGraphicsUtil().printStoreGraphic(180, 550, imageName);


            printer.getEmulation().getGraphicsUtil().printBox(0, 240, 800, 540, 4);

            //绘制横线
            printer.getEmulation().getGraphicsUtil().printLine(0, 290, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 340, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 390, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 440, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 490, 800, 4, PPLBDraw.Draw_Black);
//            printer.getEmulation().getGraphicsUtil().printLine(0, 520, 800, 4, PPLBDraw.Draw_Black);
//            printer.getEmulation().getGraphicsUtil().printLine(50,20,4,480, PPLBDraw.Draw_Black);
//
//            //绘制竖线
            printer.getEmulation().getGraphicsUtil().printLine(200, 240, 4, 300, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(300, 240, 4, 300, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(400, 240, 4, 300, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(520, 240, 4, 300, PPLBDraw.Draw_Black);

            //特别提醒
            if (footer.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, false, false, false, false,
                        imageName, footer, PPLBOrient.Clockwise_0_Degrees, 600);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 580, imageName);
            }


            //班组
            if (group.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                        imageName, group, PPLBOrient.Clockwise_0_Degrees, 120);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(450, 580, imageName);
            }

            //打印日期
            if (printDate.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                        imageName, printDate, PPLBOrient.Clockwise_0_Degrees, 250);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(580, 580, imageName);
            }


//            //填制表头数据
            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "电池型号", PPLBOrient.Clockwise_0_Degrees, 200);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(40, 250, imageName);


            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "配组", PPLBOrient.Clockwise_0_Degrees, 100);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(225, 250, imageName);

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "组数", PPLBOrient.Clockwise_0_Degrees, 100);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(325, 250, imageName);

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "总数", PPLBOrient.Clockwise_0_Degrees, 100);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(425, 250, imageName);

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "丝网", PPLBOrient.Clockwise_0_Degrees, 800);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(620, 250, imageName);


            JSONArray body = content.getJSONArray("body");
            //绘制表体数据
            int y = 250;
            for (int i = 0; i < body.size(); i++) {
                y = y + 50;
                JSONObject item = body.getJSONObject(i);
                if (item.getString("batteryNo") != null && item.getString("batteryNo").length() > 0) {
                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, item.getString("batteryNo"), PPLBOrient.Clockwise_0_Degrees, 150);
                    printer.getEmulation().getGraphicsUtil().printStoreGraphic(40, y, imageName);
                }

                if (item.getString("groupNum") != null && item.getString("groupNum").length() > 0) {
                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, item.getString("groupNum"), PPLBOrient.Clockwise_0_Degrees, 100);
                    printer.getEmulation().getGraphicsUtil().printStoreGraphic(225, y, imageName);
                }

                if (item.getString("num") != null && item.getString("num").length() > 0) {
                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, item.getString("num"), PPLBOrient.Clockwise_0_Degrees, 100);
                    printer.getEmulation().getGraphicsUtil().printStoreGraphic(325, y, imageName);
                }

                if (item.getString("sum") != null && item.getString("sum").length() > 0) {
                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, item.getString("sum"), PPLBOrient.Clockwise_0_Degrees, 100);
                    printer.getEmulation().getGraphicsUtil().printStoreGraphic(425, y, imageName);
                }

                String logo = item.getString("logo");
                if (logo != null && logo.length() > 0) {

                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, logo, PPLBOrient.Clockwise_0_Degrees, 800);
                    if (logo.length() < 6) {
                        printer.getEmulation().getGraphicsUtil().printStoreGraphic(600, y, imageName);
                    } else {
                        printer.getEmulation().getGraphicsUtil().printStoreGraphic(545, y, imageName);
                    }
                }
            }
            printer.getEmulation().getSetUtil().setPrintOut(1, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void templateShSt(BarcodePrinter<USBConnection, PPLB> printer, JSONObject jsonObject) {
        byte[] buf;
        try {

            JSONObject content = jsonObject.getJSONObject(CONTENT);

            buf = encode.getBytes(content.getString("qrcode"));
            String headTitle = content.getString("headTitle") == null ? "" : content.getString("headTitle");
            String cusName = content.getString("cusName") == null ? "" : content.getString("cusName");
            String flagCode = content.getString("flagCode") == null ? "" : content.getString("flagCode");
            String printDate = content.getString("printDate") == null ? "" : content.getString("printDate");
            String shNo = content.getString("shNo") == null ? "" : content.getString("shNo");

            //setting.
            printer.getEmulation().getSetUtil().setHardwareOption(PPLBMediaType.Thermal_Transfer_Media, PPLBPrintMode.Peel_Off, 0);
            printer.getEmulation().getSetUtil().setOrientation(false);
            printer.getEmulation().getSetUtil().setStorage(PPLBStorage.Dram);//storage.
            printer.getEmulation().getSetUtil().setClearImageBuffer();
            printer.getEmulation().getSetUtil().setPrintWidth(850);
            printer.getEmulation().getSetUtil().setDarkness(15);

            String imageName = "txt" + String.format("%05d", new Random().nextInt(100000));

            //表头
            if (headTitle.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                        imageName, headTitle, PPLBOrient.Clockwise_0_Degrees, 350);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 20, imageName);
            }


            //旗号
            if (flagCode.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                        imageName, flagCode, PPLBOrient.Clockwise_0_Degrees, 500);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(360, 20, imageName);
            }


            //二维码
            printer.getEmulation().getBarcodeUtil().printQRCode(500, 200, PPLBQRCodeModel.Model_2, 8, PPLBQRCodeErrCorrect.Standard, buf);// QR Code

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, content.getString("qrcode"), PPLBOrient.Clockwise_0_Degrees, 500);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(480, 420, imageName);


            //绘制横线
            printer.getEmulation().getGraphicsUtil().printLine(0, 60, 500, 5, PPLBDraw.Draw_Black);
//
            //客户
            if (cusName.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 42, true, false, false, false,
                        imageName, cusName, PPLBOrient.Clockwise_0_Degrees, 800);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(100, 80, imageName);
            }

            JSONArray body = content.getJSONArray("body");
            JSONObject item = body.getJSONObject(0);

            //电池型号

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 38, true, false, false, false,
                    imageName, "电池型号：" + item.getString("batteryNo"), PPLBOrient.Clockwise_0_Degrees, 600);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(100, 160, imageName);

            //配组
            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 38, true, false, false, false,
                    imageName, "配组：" + item.getString("groupNum"), PPLBOrient.Clockwise_0_Degrees, 600);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(100, 240, imageName);


            //组数
            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 38, true, false, false, false,
                    imageName, "组数：" + item.getString("num"), PPLBOrient.Clockwise_0_Degrees, 600);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(100, 320, imageName);

            //总数
            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 38, true, false, false, false,
                    imageName, "总数：" + item.getString("sum"), PPLBOrient.Clockwise_0_Degrees, 600);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(100, 400, imageName);

            //等级
            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 38, true, false, false, false,
                    imageName, "等级：" + item.getString("grade"), PPLBOrient.Clockwise_0_Degrees, 600);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(100, 480, imageName);


            //组号 item.getString("shNo")
            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 38, true, false, false, false,
                    imageName, "组号：" + shNo, PPLBOrient.Clockwise_0_Degrees, 600);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(100, 560, imageName);


            //打印日期
            if (printDate.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                        imageName, printDate, PPLBOrient.Clockwise_0_Degrees, 250);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(600, 560, imageName);
            }


//            //填制表头数据
            printer.getEmulation().getSetUtil().setPrintOut(1, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void templateSh(BarcodePrinter<USBConnection, PPLB> printer, JSONObject jsonObject) {
        byte[] buf;
        try {

            JSONObject content = jsonObject.getJSONObject(CONTENT);

            buf = encode.getBytes(content.getString("qrcode"));
            String headTitle = content.getString("headTitle") == null ? "" : content.getString("headTitle");
            String cusName = content.getString("cusName") == null ? "" : content.getString("cusName");
            String receiveName = content.getString("receiveName") == null ? "" : content.getString("receiveName");
            String flagCode = content.getString("flagCode") == null ? "" : content.getString("flagCode");
            String footer = content.getString("footer") == null ? "" : content.getString("footer");
            String group = content.getString("group") == null ? "" : content.getString("group");
//            String printDate = "打印日期：2023-08-09";
            String printDate = content.getString("printDate") == null ? "" : content.getString("printDate");

            //setting.
            printer.getEmulation().getSetUtil().setHardwareOption(PPLBMediaType.Thermal_Transfer_Media, PPLBPrintMode.Peel_Off, 0);
            printer.getEmulation().getSetUtil().setOrientation(false);
            printer.getEmulation().getSetUtil().setStorage(PPLBStorage.Dram);//storage.
            printer.getEmulation().getSetUtil().setClearImageBuffer();
            printer.getEmulation().getSetUtil().setPrintWidth(850);
            printer.getEmulation().getSetUtil().setDarkness(15);

            String imageName = "txt" + String.format("%05d", new Random().nextInt(100000));

            //表头
            if (headTitle.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                        imageName, headTitle, PPLBOrient.Clockwise_0_Degrees, 350);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 20, imageName);
            }


            //旗号
            if (flagCode.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                        imageName, flagCode, PPLBOrient.Clockwise_0_Degrees, 500);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(310, 20, imageName);
            }


            //二维码
            printer.getEmulation().getBarcodeUtil().printQRCode(600, 20, PPLBQRCodeModel.Model_2, 7, PPLBQRCodeErrCorrect.Standard, buf);// QR Code

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 22, false, false, false, false,
                    imageName, content.getString("qrcode"), PPLBOrient.Clockwise_0_Degrees, 200);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(580, 175, imageName);

//            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
//                    imageName, "---------------------------------------------------------------------------------------------------------------------------",
//                    PPLBOrient.Clockwise_0_Degrees, 500);
//            printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 40, imageName);

            //绘制横线
            printer.getEmulation().getGraphicsUtil().printLine(0, 60, 500, 5, PPLBDraw.Draw_Black);
//
            //客户
            if (cusName.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 28, false, false, false, false,
                        imageName, cusName, PPLBOrient.Clockwise_0_Degrees, 600);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 80, imageName);
            }

            //收货人
            if (receiveName.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 28, false, false, false, false,
                        imageName, receiveName, PPLBOrient.Clockwise_0_Degrees, 600);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 120, imageName);
            }
            //备注


            printer.getEmulation().getGraphicsUtil().printBox(0, 200, 800, 560, 4);

            //绘制横线
            printer.getEmulation().getGraphicsUtil().printLine(0, 240, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 280, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 320, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 360, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 400, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 440, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 480, 800, 4, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(0, 520, 800, 4, PPLBDraw.Draw_Black);
//            printer.getEmulation().getGraphicsUtil().printLine(0, 520, 800, 4, PPLBDraw.Draw_Black);
//            printer.getEmulation().getGraphicsUtil().printLine(50,20,4,480, PPLBDraw.Draw_Black);
//
//            //绘制竖线
            printer.getEmulation().getGraphicsUtil().printLine(180, 200, 4, 360, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(270, 200, 4, 360, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(360, 200, 4, 360, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(460, 200, 4, 360, PPLBDraw.Draw_Black);
            printer.getEmulation().getGraphicsUtil().printLine(600, 200, 4, 360, PPLBDraw.Draw_Black);

            //特别提醒
            if (footer.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, false, false, false, false,
                        imageName, footer, PPLBOrient.Clockwise_0_Degrees, 600);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(0, 580, imageName);
            }


            //班组
            if (group.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                        imageName, group, PPLBOrient.Clockwise_0_Degrees, 120);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(450, 580, imageName);
            }

            //打印日期
            if (printDate.length() > 0) {
                printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                        imageName, printDate, PPLBOrient.Clockwise_0_Degrees, 250);
                printer.getEmulation().getGraphicsUtil().printStoreGraphic(580, 580, imageName);
            }


//            //填制表头数据
            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "电池型号", PPLBOrient.Clockwise_0_Degrees, 200);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(40, 208, imageName);


            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "配组", PPLBOrient.Clockwise_0_Degrees, 100);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(200, 208, imageName);

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "组数", PPLBOrient.Clockwise_0_Degrees, 100);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(290, 208, imageName);

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "总数", PPLBOrient.Clockwise_0_Degrees, 100);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(380, 208, imageName);

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "等级", PPLBOrient.Clockwise_0_Degrees, 100);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(490, 208, imageName);

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 26, true, false, false, false,
                    imageName, "丝网", PPLBOrient.Clockwise_0_Degrees, 800);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(640, 208, imageName);


            JSONArray body = content.getJSONArray("body");
            //绘制表体数据
            int y = 210;
            for (int i = 0; i < body.size(); i++) {
                y = y + 40;
                JSONObject item = body.getJSONObject(i);
                if (item.getString("batteryNo") != null && item.getString("batteryNo").length() > 0) {
                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, item.getString("batteryNo"), PPLBOrient.Clockwise_0_Degrees, 150);
                    printer.getEmulation().getGraphicsUtil().printStoreGraphic(20, y, imageName);
                }

                if (item.getString("groupNum") != null && item.getString("groupNum").length() > 0) {
                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, item.getString("groupNum"), PPLBOrient.Clockwise_0_Degrees, 100);
                    printer.getEmulation().getGraphicsUtil().printStoreGraphic(200, y, imageName);
                }

                if (item.getString("num") != null && item.getString("num").length() > 0) {
                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, item.getString("num"), PPLBOrient.Clockwise_0_Degrees, 100);
                    printer.getEmulation().getGraphicsUtil().printStoreGraphic(290, y, imageName);
                }

                if (item.getString("sum") != null && item.getString("sum").length() > 0) {
                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, item.getString("sum"), PPLBOrient.Clockwise_0_Degrees, 100);
                    printer.getEmulation().getGraphicsUtil().printStoreGraphic(380, y, imageName);
                }

                if (item.getString("grade") != null && item.getString("grade").length() > 0) {
                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, item.getString("grade"), PPLBOrient.Clockwise_0_Degrees, 100);
                    printer.getEmulation().getGraphicsUtil().printStoreGraphic(490, y, imageName);
                }

                String logo = item.getString("logo");
                if (logo != null && logo.length() > 0) {

                    printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, 25, true, false, false, false,
                            imageName, logo, PPLBOrient.Clockwise_0_Degrees, 800);
                    if (logo.length() < 6) {
                        printer.getEmulation().getGraphicsUtil().printStoreGraphic(640, y, imageName);
                    } else {
                        printer.getEmulation().getGraphicsUtil().printStoreGraphic(640, y, imageName);
                    }
                }
            }
            printer.getEmulation().getSetUtil().setPrintOut(1, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void PPLBFunctionText(JSONObject jsonObject, Activity context) {

        BarcodePrinter<USBConnection, PPLB> printer = new BarcodePrinter<USBConnection, PPLB>();
        try {
            //if you use BluetoothConnection instead of TCPConnection , you must implements onActivityResult(...) callback function
            //with calling printer.getConnection().onActivityResult(...)
            printer.setConnection(new USBConnection(context, device));
            printer.setEmulation(new PPLB());
            //printer.setEnabledLogger(true);//If you need logger file. Please enable this line code.

            printer.getConnection().open();

            JSONObject content = jsonObject.getJSONObject(CONTENT);

            String flagCode = content.getString("flagCode") == null ? "" : content.getString("flagCode");
            int x = content.getInteger("x") == null ? 40 : content.getInteger("x");
            int y = content.getInteger("y") == null ? 150 : content.getInteger("y");
            int fontSize = content.getInteger("fontSize") == null ? 250 : content.getInteger("fontSize");


            //setting.
            printer.getEmulation().getSetUtil().setHardwareOption(PPLBMediaType.Thermal_Transfer_Media, PPLBPrintMode.Peel_Off, 0);
            printer.getEmulation().getSetUtil().setOrientation(false);
            printer.getEmulation().getSetUtil().setStorage(PPLBStorage.Dram);//storage.
            printer.getEmulation().getSetUtil().setClearImageBuffer();
            printer.getEmulation().getSetUtil().setPrintWidth(850);
            printer.getEmulation().getSetUtil().setDarkness(15);

//            printer.getEmulation().getSetUtil().;
            //data.

            String imageName = "txt" + String.format("%05d", new Random().nextInt(100000));

            printer.getEmulation().getTextUtil().storeTextGraphic(Typeface.DEFAULT, fontSize, true, false, false, false,
                    imageName, flagCode, PPLBOrient.Clockwise_0_Degrees, 800);
            printer.getEmulation().getGraphicsUtil().printStoreGraphic(x, y, imageName);

            printer.getEmulation().getSetUtil().setPrintOut(1, 1);

            printer.getEmulation().printOut();
            printer.getConnection().close();
        } catch (Exception ex) {
            try {
                printer.getConnection().close();
            } catch (Exception e) {
            } finally {
                Log.e(TAG, null, ex);
            }
        }
    }

    private void PPLBFunction(JSONObject jsonObject, Activity context) {

        BarcodePrinter<USBConnection, PPLB> printer = new BarcodePrinter<USBConnection, PPLB>();

        try {
            //if you use BluetoothConnection instead of TCPConnection , you must implements onActivityResult(...) callback function
            //with calling printer.getConnection().onActivityResult(...)
            printer.setConnection(new USBConnection(context, device));
            printer.setEmulation(new PPLB());
            //printer.setEnabledLogger(true);//If you need logger file. Please enable this line code.

            printer.getConnection().open();
            String billType = "SO";
            if (jsonObject.containsKey("billType")) {
                billType = jsonObject.getString("billType");
            }
            if (billType == null || billType.length() == 0 || billType.equals("SO")) {
                template(printer, jsonObject);
            } else if (billType.equals("SH")) {
                templateSh(printer, jsonObject);
            } else {
                templateShSt(printer, jsonObject);
            }

            printer.getEmulation().printOut();
            printer.getConnection().close();
        } catch (Exception ex) {
            try {
                printer.getConnection().close();
            } catch (Exception e) {
            } finally {
                Log.e(TAG, null, ex);
            }
        }
    }


}
